package com.mao.filter;

import com.alibaba.fastjson.JSON;
import com.mao.common.BaseContext;
import com.mao.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    private static final AntPathMatcher apm =new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求
        String uri = request.getRequestURI();
        log.info("拦截到请求{}",uri);
        //2.定义直接放行的请求
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",//移动端发送短信
                "/user/login",//移动端登陆
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //3.检验是否有不用拦截的请求
        boolean r = check(uris, uri);
        if (r){
            log.info("本次请求无需拦截");
            filterChain.doFilter(request,response);
            return;
        }
        //4-1员工.需要拦截，然后检查是否在登录状态
        if (request.getSession().getAttribute("employee")!=null) {
            log.info("已登陆，无需拦截");
            Long employeeId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request,response);
            return;
        }

        //4-2客户.需要拦截，然后检查是否在登录状态
        if (request.getSession().getAttribute("user")!=null) {
            log.info("已登陆，无需拦截");
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        //5.如果未登录，以输出流方式向客户端响应响应数据，让前端判断跳转到登录页面
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] uris,String uri){
        for (int i = 0; i < uris.length; i++) {
            if ((apm.match(uris[i], uri))==true) {
                return true;
            }
        }
        return false;
    }
}
